<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepSeek API 测试工具</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        input, textarea, select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        textarea {
            height: 150px;
            resize: vertical;
        }
        button {
            background: #4CAF50;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        button:hover {
            background: #45a049;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
            white-space: pre-wrap;
            font-family: monospace;
            font-size: 12px;
        }
        .success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .info {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 DeepSeek API 测试工具</h1>
        <p>这个工具可以帮助您测试DeepSeek API的连接和响应解析。</p>
        
        <div class="form-group">
            <label for="apiKey">DeepSeek API 密钥:</label>
            <input type="password" id="apiKey" placeholder="请输入您的DeepSeek API密钥 (sk-...)">
        </div>
        
        <div class="form-group">
            <label for="surname">姓氏:</label>
            <input type="text" id="surname" value="李" maxlength="2">
        </div>
        
        <div class="form-group">
            <label for="gender">性别:</label>
            <select id="gender">
                <option value="male">男孩</option>
                <option value="female">女孩</option>
            </select>
        </div>
        
        <div class="form-group">
            <label for="count">生成数量:</label>
            <select id="count">
                <option value="3">3个</option>
                <option value="6" selected>6个</option>
            </select>
        </div>
        
        <button onclick="testAPI()" id="testBtn">🚀 测试 API</button>
        <button onclick="clearResult()">🗑️ 清除结果</button>
        
        <div id="result"></div>
    </div>

    <script>
        async function testAPI() {
            const apiKey = document.getElementById('apiKey').value.trim();
            const surname = document.getElementById('surname').value.trim();
            const gender = document.getElementById('gender').value;
            const count = document.getElementById('count').value;
            
            if (!apiKey) {
                showResult('请输入DeepSeek API密钥', 'error');
                return;
            }
            
            if (!surname) {
                showResult('请输入姓氏', 'error');
                return;
            }
            
            const testBtn = document.getElementById('testBtn');
            testBtn.textContent = '测试中...';
            testBtn.disabled = true;
            
            const genderText = gender === 'male' ? '男孩' : '女孩';
            const prompt = `请为姓氏"${surname}"的${genderText}生成${count}个双字名，要求来自唐诗。

严格按照JSON格式返回，示例格式：
[
  {
    "name": "清漪",
    "pinyin": "qīng yī", 
    "gender": "${gender}",
    "length": 2,
    "type": "tang",
    "source": "李白《将进酒》",
    "original": "君不见黄河之水天上来",
    "meaning": "清：清澈纯净；漪：水波纹。寓意心如止水，纯净美好。",
    "fullName": "${surname}清漪"
  }
]

现在请生成${count}个符合要求的名字，只返回JSON数组，不要任何其他文字：`;
            
            try {
                showResult('正在调用DeepSeek API...', 'info');
                
                const response = await fetch('https://api.deepseek.com/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${apiKey}`,
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        model: 'deepseek-chat',
                        messages: [
                            {
                                role: 'system',
                                content: '你是中文取名专家，专门从古诗词中选取名字。必须严格按照JSON数组格式返回结果，不要任何额外文字。'
                            },
                            {
                                role: 'user',
                                content: prompt
                            }
                        ],
                        temperature: 0.8,
                        max_tokens: 2000,
                        stream: false
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(`API调用失败: ${response.status} ${errorData.error?.message || response.statusText}`);
                }

                const data = await response.json();
                const content = data.choices?.[0]?.message?.content || '';
                
                showResult(`✅ API调用成功！\n\n📋 原始响应:\n${content}\n\n🔍 解析测试:`, 'success');
                
                // 测试解析
                const parsed = testJSONParsing(content);
                if (parsed) {
                    document.getElementById('result').innerHTML += `\n\n✅ JSON解析成功！\n生成了${parsed.length}个名字:\n${JSON.stringify(parsed, null, 2)}`;
                } else {
                    document.getElementById('result').innerHTML += '\n\n❌ JSON解析失败，请检查响应格式';
                }
                
            } catch (error) {
                showResult(`❌ 测试失败:\n${error.message}`, 'error');
            } finally {
                testBtn.textContent = '🚀 测试 API';
                testBtn.disabled = false;
            }
        }
        
        function testJSONParsing(content) {
            console.log('测试JSON解析，原始内容:', content);
            
            // 尝试多种JSON提取方式
            let jsonMatch = content.match(/\[[\s\S]*?\]/);
            
            // 如果没找到，尝试更宽松的匹配
            if (!jsonMatch) {
                jsonMatch = content.match(/```json\s*([\s\S]*?)\s*```/);
                if (jsonMatch) {
                    jsonMatch[0] = jsonMatch[1];
                }
            }
            
            // 如果还没找到，尝试直接解析整个内容
            if (!jsonMatch) {
                // 移除可能的markdown标记
                const cleanContent = content.replace(/```json|```/g, '').trim();
                if (cleanContent.startsWith('[') && cleanContent.endsWith(']')) {
                    jsonMatch = [cleanContent];
                }
            }
            
            if (jsonMatch) {
                try {
                    const parsed = JSON.parse(jsonMatch[0]);
                    console.log('解析成功:', parsed);
                    return parsed;
                } catch (e) {
                    console.error('JSON解析失败:', e);
                }
            } else {
                console.log('未找到JSON数据');
            }
            
            return null;
        }
        
        function showResult(message, type) {
            const result = document.getElementById('result');
            result.textContent = message;
            result.className = `result ${type}`;
        }
        
        function clearResult() {
            document.getElementById('result').innerHTML = '';
        }
        
        // 页面加载时自动填入已保存的API密钥
        window.addEventListener('load', () => {
            const savedKey = localStorage.getItem('deepseek-api-key');
            if (savedKey && savedKey !== 'your-deepseek-api-key') {
                document.getElementById('apiKey').value = savedKey;
            }
        });
    </script>
</body>
</html>